import { segment } from "oicq";
import lodash from "lodash";

let groupCD = {};
let singleCD = {};
let PokeCD = {};

/**
 * 处理群聊私聊消息
 */
async function dealMsg(e) {

  //黑名单
  if (BotConfig.balckQQ && BotConfig.balckQQ.includes(Number(e.user_id))) {
    return;
  }

  //没有群昵称的用qq昵称代替
  if (!e.sender.card) {
    e.sender.card = e.sender.nickname;
  }
    
  //主人qq
  if (BotConfig.masterQQ && BotConfig.masterQQ.includes(Number(e.user_id))) {
    e.isMaster = true;
  }

  if (e.user_id == BotConfig.account.qq || typeof groupConfig == undefined) {
    return;
  }

  if (e.isGroup) {
    //禁言中
    if (e.group.mute_left > 0) {
      return;
    }
    if (groupConfig[e.group_id]) {
      e.groupConfig = groupConfig[e.group_id];
    }
  } else {
    e.group_name = "私聊";
  }

  if (!e.groupConfig) {
    e.groupConfig = groupConfig.default;
  }

  //判断冷却cd
  if (!checkLimit(e)) {
    return;
  }

  //重写reply方法，捕获发送消息失败异常
  e.replyNew = e.reply;
  e.reply = (msg, quote = false) => {
    redis.incr(`Yunzai:sendMsgNum:${BotConfig.account.qq}`);
    return e.replyNew(msg, quote).catch((err) => {
      Bot.logger.mark(err);
    });
  };

  //处理消息
  for (let val of e.message) {
    switch (val.type) {
      case "text":
        val.text = val.text.replace(/＃|井/g, "#").trim();
        if (e.msg) {
          e.msg += val.text;
        } else {
          e.msg = val.text;
        }
        break;
      case "image":
        if (!e.img) {
          e.img = [];
        }
        e.img.push(val.url);
        break;
      case "at":
        e.at = val.qq;
        break;
      case "file":
        e.file = { name: val.name, fid: val.fid };
        break;
    }
  }

  //回复消息
  if (e.source) {
    e.hasReply = true;
  }

  if (typeof YunzaiApps == "undefined") {
    return;
  }

  for (let val of command) {
    let msg = e.msg;

    //禁用功能
    if (e.groupConfig.disable && e.groupConfig.disable.length > 0) {
      if (lodash.intersection(e.groupConfig.disable, [val.type, `${val.type}.${val.name}`, "all"]).length > 0) {
        continue;
      }
    }

    //原神查询功能时，@机器人代替#号
    if (val.type == "mysInfo" && e.at && e.at == BotConfig.account.qq && msg) {
      msg = "#" + msg.replace("#", "");
    }

    if (!val.reg) {
      val.reg = "noCheck";
    }

    if (new RegExp(val.reg).test(msg) || val.reg == "noCheck") {
      let log = `[${e.group_name}] ${msg}:${val.name}`;

      if (val.reg == "noCheck") {
        Bot.logger.debug(log);
      } else {
        Bot.logger.mark(log);
      }

      if(!YunzaiApps[val.type] || !YunzaiApps[val.type][val.name]){
        Bot.logger.error(`请先export该方法：${val.type}.${val.name}`);
        return;
      }

      try {
        let res = await YunzaiApps[val.type][val.name](e);
        if (res) {
          //设置cd
          setLimit(e);
          break;
        }
      } catch (error) {
        Bot.logger.error(`${val.type}.${val.name}`);
        Bot.logger.error(error);
        break;
      }
    }
  }
}

/**
 * 设置命令冷却时间
 */
function setLimit(e) {
  if (e.isPrivate) {
    return true;
  }
  if (e.isPoke) {
    let cd = e.groupConfig.PokeCD ? e.groupConfig.PokeCD : 5000;
    PokeCD[e.group_id] = 1;
    setTimeout(() => {
      delete PokeCD[e.group_id];
    }, cd);
    return;
  }
  if (e.groupConfig.groupCD) {
    groupCD[e.group_id] = true;
    setTimeout(() => {
      delete groupCD[e.group_id];
    }, e.groupConfig.groupCD);
  }
  if (e.groupConfig.singleCD) {
    if (!singleCD[e.group_id]) {
      singleCD[e.group_id] = {};
    }
    singleCD[e.group_id][e.user_id] = true;
    setTimeout(() => {
      delete singleCD[e.group_id][e.user_id];
    }, e.groupConfig.singleCD);
  }
}

/**
 * 检查命令冷却cd，防止刷屏
 */
function checkLimit(e) {
  if (e.isPrivate) {
    return true;
  }
  if (e.isPoke) {
    if (PokeCD[e.group_id]) {
      return false;
    }
    return true;
  }
  if (e.groupConfig.groupCD && groupCD[e.group_id]) {
    return false;
  }
  if (e.groupConfig.singleCD && singleCD[e.group_id] && singleCD[e.group_id][e.user_id]) {
    return false;
  }
  return true;
}

/**
 * 群消息通知，戳一戳，新人加入，禁言
 */
async function dealGroupNotice(e) {
  if (groupConfig[e.group_id]) {
    e.groupConfig = groupConfig[e.group_id];
  }
  if (!e.groupConfig) {
    e.groupConfig = groupConfig.default;
  }

  e.reply = (msg) => {
    redis.incr(`Yunzai:sendMsgNum:${BotConfig.account.qq}`);
    e.group.sendMsg(msg);
  };

  switch (e.sub_type) {
    case "poke":
      dealPoke(e);
      break;
    case "increase":
      dealIncrease(e);
      break;
    case "ban":
      dealBan(e);
      break;
  }
}

/**
 * 戳一戳
 */
function dealPoke(e) {
  if (typeof YunzaiApps == "undefined") {
    return;
  }
  if (e.group.mute_left > 0) {
    return;
  }
  e.isPoke = true;
  e.user_id = e.operator_id;

  if (e.target_id != BotConfig.account.qq) {
    return;
  }
  if (e.groupConfig.disable) {
    if (e.groupConfig.disable.includes("all")) {
      return;
    }
    if (e.groupConfig.disable.includes("mysInfo")) {
      return;
    }
    if (e.groupConfig.disable.includes("poke")) {
      return;
    }
  }

  //黑名单
  if (BotConfig.balckQQ && BotConfig.balckQQ.includes(Number(e.user_id))) {
    return;
  }

  //主人qq
  if (BotConfig.masterQQ && BotConfig.masterQQ.includes(Number(e.user_id))) {
    e.isMaster = true;
  }

  if (!checkLimit(e)) {
    if (PokeCD[e.group_id] <= 1 && !e.isMaster) {
      e.reply([segment.at(e.user_id), "\n戳太快，冷却中。。"]);
    }

    if (PokeCD[e.group_id]) {
      PokeCD[e.group_id]++;
    }
    return;
  }

  setLimit(e);

  e.sender = { card: "" };

  YunzaiApps.mysInfo.pokeCharacter(e);
}

/**
 * 群请求通知，邀请加群
 */
function dealFriend(e) {
  if (e.sub_type == "add" || e.sub_type == "single") {
    Bot.logger.mark(`添加好友：${e.user_id}`);
    e.approve(true);
  }
}

/**
 * 群请求通知，邀请加群
 */
function dealGroupRequest(e) {
  if (e.sub_type == "invite") {
    if (!BotConfig.masterQQ || !BotConfig.masterQQ.includes(Number(e.user_id))) {
      Bot.logger.mark(`邀请加群：${e.group_name}：${e.group_id}`);
      return;
    }
    Bot.logger.mark(`主人邀请加群：${e.group_name}：${e.group_id}`);
    e.approve(true);
    Bot.sendPrivateMsg(e.user_id, `已同意加群：${e.group_name}`).catch((err) => {
      Bot.logger.error(err);
    });
  }
}

/**
 * 禁言
 */
function dealBan(e) {}

/**
 * 新人加入
 */
function dealIncrease(e) {}

export { dealMsg, dealGroupNotice, dealFriend, dealGroupRequest };
